/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2012 www.pretty-tools.com
 */

/**
 * Handles events of changing tabs and new page loading
 *
 * @author Alexander Kozlov
 */
function wsshBrowserListener()
{
    this.logger = yrprxFactory.createLogger("wsshBrowserListener");
}

wsshBrowserListener.prototype.onLoad = function(event)
{
    try
    {
        var listener = this;

        window.addEventListener("pageshow", function(e){ listener.onPageShow(e); }, false);

        if (wsshConfig.isFirstStart) { // execute following only one time just after installation
            // need to open page with instructions
            setTimeout(function() {
                // open page with instructions
                yrprxWebNavigationHelper.openInNewTab(wsshConfig.urlInstalled);
            }, 2000);
        }
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("onLoad: ", ex);
    }
}

wsshBrowserListener.prototype.onUnLoad = function(event)
{
}

wsshBrowserListener.prototype.onPageShow = function (event)
{
    var doc = event.target;

    try
    {
        if (this.logger.enabled) this.logger.debug("onPageShow: " + doc.location.href);

        if (doc.location.href.match(/\.xul$/)) // skip xul pages
            return;

        if (doc.location.href.indexOf("webslideshow-autostart") != -1) // run slide show
            this.startSlideShow();

        this.searchMagicElements(doc);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("onPageShow: ", ex);
    }
}

wsshBrowserListener.prototype.startSlideShow = function()
{
    try
    {
        var doc = window.content.document;

        var images = g_wsshImageResolver.getImages(doc);
        if (images && images.length)
            wsshWindowManager.openSlideShow(images, doc.title);
        else //TODO: think about this
            yrprxPrompt.alert(wsshResources["webslideshow.title"], wsshResources["webslideshow.can.not.find.appropriate.images"]);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("startSlideShow: ", ex);
    }
}

wsshBrowserListener.prototype.openImageLinkFullScreen = function(image)
{
    try
    {
        if (wsshConfig.fullscreenImageLink)
        {
            wsshWindowManager.openSlideShow([image]);
            return false;
        }
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("openImageLinkFullScreen: ", ex);
    }
    return true;
}

wsshBrowserListener.prototype.openRuledImageFullScreen = function(image)
{
    try
    {
        if (wsshConfig.fullscreenRuledImages)
        {
            wsshWindowManager.openSlideShow([image]);
            return false;
        }
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("openRuledImageFullScreen: ", ex);
    }
    return true;
}

wsshBrowserListener.prototype.searchMagicElements = function(doc)
{
    try
    {
        var listener = this;

        var startSlideShow = function(event) {
            event.stopPropagation();
            listener.startSlideShow();
        }

        var fullscreenDirectLink = function(event) {
            event.stopPropagation();
            return listener.openImageLinkFullScreen(this.href);
        };

        yrprxHTMLContentHelper.enumerateElementsByTagName(doc, "a", function(elem) {
            try
            {
                if ("webslideshow-start" == elem.className)
                {
                    elem.wrappedJSObject.onclick = startSlideShow;
                    elem.href = "javascript: void(0);";
                }
                else if ("webslideshow-rules" == elem.className)
                {
                    var rulesURL = elem.href;
                    elem.wrappedJSObject.onclick = function(event) {
                        event.stopPropagation();
                        wsshWindowManager.openImportRules(rulesURL);
                    };
                    elem.href = "javascript: void(0);";
                }
                else if (wsshConfig.fullscreenImageLink && g_wsshImageResolver.isDirectImageLink(elem.href))
                {
                    if (elem.wrappedJSObject && !elem.wrappedJSObject.onclick) // do not replace default behavior
                        elem.wrappedJSObject.onclick = fullscreenDirectLink;
                }
            }
            catch(ex)
            {
                if (listener.logger.enabled) listener.logger.error("searchMagicElements: Exception in 'A' handler: " + ex);
            }
        });

        var buttonsHandler = function(elem) {
            try
            {
                if ("webslideshow-start" != elem.className || elem.tagName == "INPUT" && elem.type != "button")
                    return;

                elem.wrappedJSObject.onclick = startSlideShow;
            }
            catch(ex)
            {
                if (listener.logger.enabled) listener.logger.error("searchMagicElements: Exception in handler: " + ex);
            }
        }

        yrprxHTMLContentHelper.enumerateElementsByTagName(doc, 'input', buttonsHandler);
        yrprxHTMLContentHelper.enumerateElementsByTagName(doc, 'button', buttonsHandler);

        if (wsshConfig.fullscreenRuledImages)
        {
            var ruledElements = g_wsshImageResolver.getSatisfiedElements(doc);
            for (var j in ruledElements)
            {
                var elem = ruledElements[j].elem;
                if (!elem) continue;

                if (elem.tagName == "IMG" && g_wsshImageResolver.isParentALink(elem))
                    elem = elem.parentNode;

                if (elem.wrappedJSObject && !elem.wrappedJSObject.onclick) // do not replace default behavior
                    this.createOnClickEventForRuledElement(elem, ruledElements[j].url);
            }
        }

        if (wsshConfig.useSubscriptions)
        {
            var subscription = doc.getElementById("WebSlideShow-Subscription");
            if (subscription) wsshRulesUpdateManager.checkForSubscriptionUpdate(subscription.value);
        }
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("searchMagicElements: ", ex);
    }
}

wsshBrowserListener.prototype.createOnClickEventForRuledElement = function(elem, url)
{
    var listener = this;

    elem.wrappedJSObject.onclick = function(event) {
        event.stopPropagation();
        return listener.openRuledImageFullScreen(url);
    };
}
